package com.qd.common.panda.domain.enums;

import com.cdqidi.exception.ApiException;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 优惠卷种类
 * preferential_1	订单立减
 * preferential_2	加油卡
 * preferential_3	优惠券
 * preferential_4	积分
 *
 * @author sjk
 */
public enum PreferentialCategoryEnum {
    /**
     * 固定时长
     */
    PREFERENTIAL_1("preferential_1", "订单立减"),
    PREFERENTIAL_2("preferential_2", "加油卡"),
    PREFERENTIAL_3("preferential_3", "优惠券"),
    PREFERENTIAL_4("preferential_4", "积分");

    private static final Map<String, Integer> IDX_MAP = new HashMap<>() {
        {
            put(PREFERENTIAL_1.code, 1);
            put(PREFERENTIAL_2.code, 2);
            put(PREFERENTIAL_3.code, 3);
            put(PREFERENTIAL_4.code, 4);
        }
    };
    final String code;
    final String msg;

    PreferentialCategoryEnum(String code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public String getCode() {
        return code;
    }

    public String getMsg() {
        return msg;
    }

    public static void checkCode(String code) {
        if (!StringUtils.hasLength(code)) {
            throw new ApiException("优惠卷种类不能为空");
        }
        if (Arrays.stream(PreferentialCategoryEnum.values()).filter(preferentialCategoryEnum -> preferentialCategoryEnum.getCode().equals(code)).findFirst().isEmpty()) {
            throw new ApiException("优惠卷种类ID不存在");
        }
    }

    /**
     * 提前判断，用于解决
     * Case中出现的Constant expression required
     *
     * @param code 编码
     * @return 对应的枚举类
     */
    public static PreferentialCategoryEnum getByValue(String code) {
        for (PreferentialCategoryEnum preferentialCategoryEnum : values()) {
            if (preferentialCategoryEnum.getCode().equals(code)) {
                return preferentialCategoryEnum;
            }
        }
        return null;
    }

    public static Integer getIdxByCode(String code) {
        return IDX_MAP.getOrDefault(code, 0);
    }

}
